import os
import subprocess

from ..common.config.config import getDevLanguageEnvConfig


# 校验路径是否有效
def checkPathValid(path) -> str:
    """校验路径是否有效"""
    if not path:
        raise FileNotFoundError("路径不能为空")

    # 将path转换为标准路径
    path = os.path.normpath(path)
    # 判断path是否存在
    if not os.path.exists(path):
        # 返回路径不存在的异常
        raise FileNotFoundError("路径不存在")
    return path


def handleVersionVerifyPath(path, version_verify_suffix) -> str:
    path = checkPathValid(path)
    if not version_verify_suffix:
        return path

    if path.endswith(version_verify_suffix) and os.path.exists(os.path.join(path, version_verify_suffix)):
        return path

    return os.path.join(path, version_verify_suffix)


def checkVersionForDevLanguage(dev_language_name, file_path=None) -> str:
    """根据开发语言检测版本"""
    if dev_language_name is None:
        raise Exception("未指定开发语言")

    devLanguageEnvConfig = getDevLanguageEnvConfig()

    # 获取版本检测命令
    devLanguageConfig = next(
        (item for item in devLanguageEnvConfig if item['name'].lower() == dev_language_name.lower()),
        None)
    version_command = devLanguageConfig['version_command']
    if version_command is None:
        raise Exception(f"未找到 {dev_language_name} 语言所对应的版本检测命令")

    if file_path is not None:
        # 处理路径
        file_path = handleVersionVerifyPath(file_path, devLanguageConfig['version_verify_suffix'])
        version_command = os.path.join(file_path, version_command)
        print("执行命令：", version_command)

    return checkVersionForCommand(version_command)


def checkVersionForCommand(command) -> str:
    """根据命令检测版本"""
    if not command:
        raise Exception("命令不能为空")

    # 将命令字符串转换为列表
    command = command.split()
    try:
        output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
        # print("版本检测结果：", output.splitlines()[0].decode().strip())
        return output.splitlines()[0].decode().strip()
    except subprocess.CalledProcessError as e:
        raise Exception(f"Error：" + e.output.decode('gbk', 'ignore'))


def checkAllDevLanguageVersion() -> dict:
    """检测所有语言的版本"""
    devLanguageEnvConfig = getDevLanguageEnvConfig()
    for item in devLanguageEnvConfig:
        try:
            item['version'] = checkVersionForCommand(item['version_command'])
        except Exception as e:
            print(e)
    return devLanguageEnvConfig
